(function(KIT, RES) {

  //region private

  //初始化菜单树
  var _initTree = function() {
    $("#menuTree").g_jstree({
      data: {
        url: RES.URL_ROOT + "/menu/getMenusTree"
      },
      onselected: function(element, inst, $node) {
        _clearFormBtn();
        _changeView(false, true);

        var id = $node.id;

        if($(".menu-root").hasClass("menu-root-clicked")) {
          $(".menu-root").removeClass("menu-root-clicked");
        }

        rapid.get({
          url: RES.URL_ROOT + "/menu/getMenuById",
          data: "menuId=" + id,
          success: function(data) {
            $(".inner-form-title").html(data.type_ch + "维护").data("type", data.type);

            var parent = $("#comMenuType").parent();
            $("#comMenuType").remove();
            var html = "<input id='comMenuType' type='text' class='g-control' name='type_ch' readonly='readonly' />";
            parent.append(html);

            $("#frmMenuView").data("menuInfo", data);
            KIT.fillForm("#frmMenuView", data);
            KIT.fillForm("#frmMenuEdit", null);

            var btns = "";
            switch(data.type) {
              case "1": //模块
                btns = _formBtn._createModuleBtn();
                break;
              case "2": //应用程序
                btns = _formBtn._createAppBtn();
                break;
              case "3": //功能
                btns = _formBtn._createFuncBtn();
                break;
              default:
                break;
            }

            $(".inner-form-button").html(btns);
          }
        });
      }
    });
  };

  //初始化按钮
  var _initBtn = function() {
    $(".menu-root").on("click", function() {
      if(!$(this).hasClass("menu-root-clicked")) {
        $(this).addClass("menu-root-clicked");

        $(".menu-leaf a.jstree-clicked").removeClass("jstree-clicked");
        _changeView(true, false);
        $(".inner-form-title").removeData("type");

        $("#menuIdEdit").val("");
        $("#menuPidEdit").val("");
        $("#frmMenuView").removeData("menuInfo");
        KIT.fillView("#frmMenuView", null);
        KIT.fillForm("#frmMenuEdit", null);
      }
    });

    //菜单管理节点添加模块
    $("#btnAddModule").on("click", function() {
      _clearFormBtn();
      _changeView(false, false);

      $(".inner-form-title").html("添加模块").data("type", "1");

      //_renderMenuType("1", true);
      _initPicker("1");
      _initPickers();
      rapid("#prkMenuType").picker().value("1").text("模块");
      rapid("#rdoIsEnabled [name='enabled']").radio().filter("value=1").get().check();
      rapid("#rdoIsVisible [name='visible']").radio().filter("value=1").get().check();
      var btns = _formBtn._createEditBtn();
      $(".inner-form-button").html(btns);
    });

    //菜单管理节点添加应用程序
    $("#btnAddApp").on("click", function() {
      _clearFormBtn();
      _changeView(false, false);

      $(".inner-form-title").html("添加应用程序").data("type", "2");

      //_renderMenuType("2", true);
      _initPicker("2");
      _initPickers();
      rapid("#prkMenuType").picker().value("2").text("应用程序");
      rapid("#rdoIsEnabled [name='enabled']").radio().filter("value=1").get().check();
      rapid("#rdoIsVisible [name='visible']").radio().filter("value=1").get().check();
      var btns = _formBtn._createEditBtn();
      $(".inner-form-button").html(btns);
    });

    //添加模块
    $(".inner-form-button").delegate("#innerAddModule", "click", function() {
      _clearFormBtn();
      _changeView(false, false);

      //_renderMenuType("1", true);
      _initPicker("1");
      _initPickers();
      rapid("#prkMenuType").picker().value("1").text("模块");
      rapid("#rdoIsEnabled [name='enabled']").radio().filter("value=1").get().check();
      rapid("#rdoIsVisible [name='visible']").radio().filter("value=1").get().check();
      var data = $("#frmMenuView").data("menuInfo");
      KIT.fillForm("#frmMenuEdit", {pid: data.id, id: null});
      $(".inner-form-title").html("添加模块").data("type", "1");
      //$("#comEnabled option:first").prop("selected", 'selected');
      //$("#comVisible option:first").prop("selected", 'selected');

      var btns = _formBtn._createEditBtn();
      $(".inner-form-button").html(btns);
    });

    //添加应用程序
    $(".inner-form-button").delegate("#innerAddApp", "click", function() {
      _clearFormBtn();
      _changeView(false, false);

      //_renderMenuType("2", true);
      _initPicker("2");
      _initPickers();
      rapid("#prkMenuType").picker().value("2").text("应用程序");
      rapid("#rdoIsEnabled [name='enabled']").radio().filter("value=1").get().check();
      rapid("#rdoIsVisible [name='visible']").radio().filter("value=1").get().check();
      var data = $("#frmMenuView").data("menuInfo");
      KIT.fillForm("#frmMenuEdit", {pid: data.id, id: null});
      $(".inner-form-title").html("添加应用程序").data("type", "1");
      //$("#comEnabled option:first").prop("selected", 'selected');
      //$("#comVisible option:first").prop("selected", 'selected');

      var btns = _formBtn._createEditBtn();
      $(".inner-form-button").html(btns);
    });

    //添加功能
    $(".inner-form-button").delegate("#innerAddFunc", "click", function() {
      _clearFormBtn();
      _changeView(false, false);

      //_renderMenuType("3", true);
      _initPicker("3");
      _initPickers();
      rapid("#prkMenuType").picker().value("3").text("功能");
      rapid("#rdoIsEnabled [name='enabled']").radio().filter("value=1").get().check();
      rapid("#rdoIsVisible [name='visible']").radio().filter("value=1").get().check();
      var data = $("#frmMenuView").data("menuInfo");
      KIT.fillForm("#frmMenuEdit", {pid: data.id, id: null});
      $(".inner-form-title").html("添加功能").data("type", "2");
      //$("#comEnabled option:first").prop("selected", 'selected');
      //$("#comVisible option:first").prop("selected", 'selected');

      var btns = _formBtn._createEditBtn();
      $(".inner-form-button").html(btns);
    });

    //修改
    $(".inner-form-button").delegate("#innerEdit", "click", function() {
      _clearFormBtn();
      _changeView(false, false);

      //_renderMenuType($(".inner-form-title").data("type"), true);

      _initPicker($(".inner-form-title").data("type"));
      _initPickers();
      var data = $("#frmMenuView").data("menuInfo");
      KIT.fillForm("#frmMenuEdit", data);
      rapid("#prkMenuType").picker().value(data.type).text(data.type_ch);
      rapid("#menu_types").picker().value(data.menu_type).text(data.menu_type_ch);
      rapid("#rdoIsEnabled [name='enabled']").radio().filter("value=" + data.enabled).get().check();
      rapid("#rdoIsVisible [name='visible']").radio().filter("value=" + data.visible).get().check();
      $(".inner-form-title").html("修改" + data.type_ch);

      var btns = _formBtn._createEditBtn();
      $(".inner-form-button").html(btns);
    });

    //删除
    $(".inner-form-button").delegate("#innerDel", "click", function() {
      var id = $("#menuTree").g_jstree().getselected().id;
      if(!rapid.isEmpty(id)) {
        rapid.confirm("当前操作会同时删除相关联的子级数据，确定要删除吗？", function(e) {
          if(!e) {
            return;
          }
          rapid.post({
            url: RES.URL_ROOT + "/menu/deleteMenuById",
            data: "menuId=" + id,
            success: function(result) {
              if(!$(".menu-root").hasClass("menu-root-clicked")) {
                $(".menu-root").addClass("menu-root-clicked");
              }

              $(".menu-leaf a.jstree-clicked").removeClass("jstree-clicked");

              $("#menuIdEdit").val("");
              $("#menuPidEdit").val("");

              $("#frmMenuView").removeData("menuInfo");

              KIT.fillView("#frmMenuView", null);
              KIT.fillForm("#frmMenuEdit", null);

              _clearFormBtn();
              _changeView(true, false);

              $("#menuTree").g_jstree().refresh();
              rapid.success();
            }
          });
        });
      }
    });

    //保存
    $(".inner-form-button").delegate("#innerSave", "click", function() {
      if(!_startVaild()) {
        return;
      }
      rapid.confirm("确定要保存吗？", function(e) {
        if(!e) {
          return;
        }
        var edit = rapid("#frmMenuEdit").serializeJson();
        var _code = edit.code;
        if(!/^[0-9]+$/.test(_code)) {
          rapid.warn("编号必须全是数字");
          return false;
        }
        var _str = edit.menu_type;
        if(edit.pid != null && edit.pid != 0) {
          if(_str != "ORDINARYMENU") {
            if(edit.menu_code == null || edit.menu_code == "") {
              rapid.warn("非普通菜单编号不能为空！");
              return false;
            }
          }
        }
        rapid.post({
          url: RES.URL_ROOT + "/menu/saveMenu",
          data: edit,
          success: function(result) {
            var view = $("#frmMenuView").data("menuInfo");
            if(!rapid.isEmpty(view)) {
              var data = $.extend(true, {}, edit, {pid: view.pid, id: view.id});
              $("#frmMenuView").data("menuInfo", data);
              KIT.fillView("#frmMenuView", data);
            }
            KIT.fillForm("#frmMenuEdit", null);

            _renderMenuForm();

            $("#menuTree").g_jstree().refresh();
            rapid.success();
          }
        });
      });
    });

    //取消
    $(".inner-form-button").delegate("#innerCancel", "click", function() {
      _renderMenuForm();
    });
  };

  //表单按钮
  var _formBtn = {
    _innerAddModule: function() {
      //添加模块
      return KIT.html.button({
        id: "innerAddModule",
        style: 1,
        text: "添加模块"
      });
    },
    _innerAddApp: function() {
      //添加应用程序
      return KIT.html.button({
        id: "innerAddApp",
        style: 1,
        text: "添加应用程序"
      });
    },
    _innerAddFunc: function() {
      //添加功能
      return KIT.html.button({
        id: "innerAddFunc",
        style: 1,
        text: "添加功能"
      });
    },
    _innerEdit: function() {
      //修改
      return KIT.html.editButton({id: "innerEdit"});
    },
    _innerDel: function() {
      //删除
      return KIT.html.removeButton({id: "innerDel"});
    },
    _innerSave: function() {
      //保存
      return KIT.html.saveButton({id: "innerSave"});
    },
    _innerCancel: function() {
      //取消
      return KIT.html.cancelButton({id: "innerCancel"});
    },
    _createModuleBtn: function() {
      //创建模块所含按钮
      return this._innerAddModule() + this._innerAddApp() + this._innerEdit() + this._innerDel();
    },
    _createAppBtn: function() {
      //创建应用程序所含按钮
      return this._innerAddFunc() + this._innerEdit() + this._innerDel();
    },
    _createFuncBtn: function() {
      //创建功能所含按钮
      return this._innerEdit() + this._innerDel();
    },
    _createEditBtn: function() {
      //创建编辑所含按钮
      return this._innerSave() + this._innerCancel();
    }
  }

  //清空表单按钮
  var _clearFormBtn = function() {
    $(".inner-form-button").html("");
  }

  //调整页面高度
  var _resize = function() {
    var bw = $(document).width();
    var bh = $(document).height() - 30;

    var colLeft = $(".menu-col-left");
    var colRight = $(".menu-col-right");

    colLeft.height(bh);
    colRight.height(bh);

    if(colLeft.width() + colRight.width() >= bw) {
      colLeft.addClass("col-resize");
    } else {
      colLeft.removeClass("col-resize");
    }

    var rw = colRight.width();
    var rh = colRight.height();

    var innerButton = $(".inner-button");
    var iw = innerButton.width();
    var ih = innerButton.height();

    var th = (rh - ih) / 2, tw = 15;
    if(rw > iw) {
      tw = (rw - iw) / 2;
    }

    innerButton.attr("style", "position:absolute; top:" + th + "px; left:" + tw + "px");
  }

  //切换视图
  var _changeView = function(b, v) {
    var button = $(".inner-button"),
      form = $(".inner-form"),
      view = $(".inner-view"),
      edit = $(".inner-edit");

    if(b) { //菜单管理视图
      _jdugeClass(view, "inner-block", "inner-none");
      _jdugeClass(edit, "inner-block", "inner-none");
      _jdugeClass(form, "inner-block", "inner-none");
      _jdugeClass(button, "inner-none", "inner-inline");
    } else {
      if(v) { //查看视图
        _jdugeClass(button, "inner-inline", "inner-none");
        _jdugeClass(edit, "inner-block", "inner-none");
        _jdugeClass(view, "inner-none", "inner-block");
        _jdugeClass(form, "inner-none", "inner-block");
      } else { //编辑视图
        _jdugeClass(button, "inner-inline", "inner-none");
        _jdugeClass(view, "inner-block", "inner-none");
        _jdugeClass(edit, "inner-none", "inner-block");
        _jdugeClass(form, "inner-none", "inner-block");
      }
    }
  }

  //判断视图样式
  var _jdugeClass = function($this, removeClass, addClass) {
    $this.removeClass(removeClass);
    if(!$this.hasClass(addClass)) {
      $this.addClass(addClass);
    }
  }

  //绘制菜单类型下拉列表
  //var _renderMenuType = function(type, flag) {
  //  var parent = $("#comMenuType").parent();
  //  $("#comMenuType").remove();
  //  var url = kit.URL_ROOT + "/menu/getMenuTypeList";
  //  if(flag) {
  //    url = kit.URL_ROOT + "/menu/getMenuType";
  //  }
  //
  //  rapid.get({
  //    url: url,
  //    data: "type=" + type,
  //    success: function(data) {
  //      var html = "<select class='g-control' id='comMenuType' name='type'>";
  //      if(flag) {
  //        html += "<option value='" + data.value + "' selected='selected'>" + data.text + "</option>";
  //      } else {
  //        for(var i = 0; i < data.length; i++) {
  //          var selected = "";
  //          if(i == 0) {
  //            selected = " selected='selected' ";
  //          }
  //          html += "<option value='" + data[i].value + "'" + selected + ">" + data[i].text + "</option>";
  //        }
  //      }
  //
  //      parent.append(html);
  //    }
  //  });
  //};

  var _initPicker = function(type) {
    rapid("#prkMenuType").picker({
      tip: "请选择...",
      dataSource: {
        url: RES.URL_ROOT + "/menu/getMenuType",
        data: {type: type}
      }
    });
  };
  var _initPickers = function() {
    rapid("#menu_types").picker({
      dataSource: {
        textField: "codename",
        valueField: "customid",
        url: RES.URL_ROOT + "/menu/getMenuTypePicker"
      }
    });
  };
  //绘制菜单表格
  var _renderMenuForm = function() {
    _clearFormBtn();
    var bo = false;

    var pid = $("#menuPidEdit").val();
    if(rapid.isEmpty($("#menuIdEdit").val())) { //新增数据
      if(rapid.isEmpty(pid)) { //菜单管理节点新增数据
        bo = true;
        _changeView(true, false);
      } else {
        if(pid == "0") { //根节点新增数据
          _changeView(false, true);
        } else { //子节点新增数据
          _changeView(false, true);
        }
      }
    } else { //修改数据
      if(pid == "0") { //根节点修改数据
        _changeView(false, true);
      } else { //子节点修改数据
        _changeView(false, true);
      }
    }

    var btns = "";
    if(!bo) {
      var type = $(".inner-form-title").data("type");
      var title = "";

      switch(type) {
        case "1": //模块
          btns = _formBtn._createModuleBtn();
          title = "模块维护";
          break;
        case "2": //应用程序
          btns = _formBtn._createAppBtn();
          title = "应用程序维护";
          break;
        case "3": //功能
          btns = _formBtn._createFuncBtn();
          title = "功能维护";
          break;
        default:
          break;
      }

      $(".inner-form-title").html(title);
    } else {
      $(".inner-form-title").removeData("type");
    }

    $(".inner-form-button").html(btns);
    KIT.fillForm("#frmMenuEdit", null);
  };
  //endregion

  var _initRadio = function() {
    KIT.html.selectorList({
      label: "状态",
      containerId: "divIsEnabled",  //容器id
      id: "rdoIsEnabled",
      name: "enabled",
      type: "R",    //C：CheckboxList R：RadioList
      defultValue: "1",   //默认选中的值
      data: KIT.ARR_STATE
    });

    KIT.html.selectorList({
      label: "显隐",
      containerId: "divIsVisible",  //容器id
      id: "rdoIsVisible",
      name: "visible",
      type: "R",    //C：CheckboxList R：RadioList
      defultValue: "1",   //默认选中的值
      data: KIT.ARR_WHETHER
    });
  };

  function _initVaild() {

    rapid.ui("#txtName_Edit", {
      validator: {
        rules: {required: true, maxlength: 50}
      }
    });
    rapid.ui("#txtCode_Edit", {
      validator: {
        rules: {required: true, maxlength: 20}
      }
    });
    rapid.ui("#prkMenuType", {
      validator: {
        rules: {required: true, maxlength:50}
      }
    });

    rapid.ui("#txtSort_ID_Edit", {
      validator: {
        rules: {
          integer: true,
          min: 0
        }
      }
    });
  }

  function _startVaild() {

    if(!rapid.ui("#txtName_Edit").valid()) {
      return false;
    }

    if(!rapid.ui("#prkMenuType").valid()) {
      return false;
    }

    if(!rapid.ui("#txtSort_ID_Edit").valid()) {
      return false;
    }
    if(!rapid.ui("#menu_types").valid()) {
      return false;
    }
    return true;
  }

  rapid.Page.create()(function() {
    _resize();

    _initTree();
    _initBtn();
    //_initRadio();
    _initVaild();
    var rt;
    $(window).resize(function() {
      clearTimeout(rt);
      rt = setTimeout(_resize, 150);
    });
  }).init();
})(rapid.kit, rapid.res);

